package metric

import (
	"log"

	"gddgame.cc/galaxy/binocle"
	"github.com/toolkits/nux"
)

func Memory(agent binocle.Service) error {
	agent.AddMetrics().Collect(func() map[string]float32 {
		m, err := nux.MemInfo()
		if err != nil {
			log.Println(err)
			return nil
		}

		memFree := m.MemFree + m.Buffers + m.Cached
		if m.MemAvailable > 0 {
			memFree = m.MemAvailable
		}
		memUsed := m.MemTotal - memFree

		pmemFree := 0.0
		pmemUsed := 0.0
		if m.MemTotal != 0 {
			pmemFree = float64(memFree) * 100.0 / float64(m.MemTotal)
			pmemUsed = float64(memUsed) * 100.0 / float64(m.MemTotal)
		}

		pswapFree := 0.0
		pswapUsed := 0.0
		if m.SwapTotal != 0 {
			pswapFree = float64(m.SwapFree) * 100.0 / float64(m.SwapTotal)
			pswapUsed = float64(m.SwapUsed) * 100.0 / float64(m.SwapTotal)
		}

		return map[string]float32{
			"mem.memtotal":         float32(m.MemTotal),
			"mem.memused":          float32(memUsed),
			"mem.memfree":          float32(memFree),
			"mem.swaptotal":        float32(m.SwapTotal),
			"mem.swapused":         float32(m.SwapUsed),
			"mem.swapfree":         float32(m.SwapFree),
			"mem.memfree.percent":  float32(pmemFree),
			"mem.memused.percent":  float32(pmemUsed),
			"mem.swapfree.percent": float32(pswapFree),
			"mem.swapused.percent": float32(pswapUsed),
		}
	})
	return nil
}
